package cn.huiyunche.driver.datasync.controller;

import cn.huiyunche.base.service.model.TmsOrder;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.driver.service.FetchTmsOrder;
import cn.huiyunche.driver.service.OrderService;
import com.beust.jcommander.internal.Lists;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import org.joda.time.format.DateTimeFormatter;
import java.util.List;


/**
 * 运单Controller
 *
 * @author lm
 */
@Controller
@RequestMapping("/ordersync")
public class OrderSyncController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderSyncController.class);

    @Autowired
    private FetchTmsOrder fetchTmsOrder = null;

    @Autowired
    private OrderService orderService = null;

    /**
     * 从TMS抓取单条订单
     * @param orderCode
     * @return
     **/
    @RequestMapping(value = "/importSingleOrder", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Object> importSingleOrder(@RequestParam("orderCode")String orderCode) {
        Result<Object> result = new Result<>(true, "查询成功");

        TmsOrder tmsOrder = fetchTmsOrder.fetchTmsOrderByOrderNo(orderCode);
        if(null!=tmsOrder){
            List<TmsOrder> tmsOrders = Lists.newArrayList();
            tmsOrders.add(tmsOrder);
            orderService.handleTmsOrders(tmsOrders);
            result.setData(tmsOrder);
        }else {
            result.setMessage("查无数据");
        }
        return result;
    }

    /**
     * 从TMS抓取单条订单
     * @param lastTime
     * @return
     **/
    @RequestMapping(value = "/importLastOrder", method = RequestMethod.GET)
    public
    @ResponseBody
    Result<Object> importLastOrder(@RequestParam("lastTime")String lastTime) {
        Result<Object> result = new Result<>(true, "查询成功");

        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        DateTime last = DateTime.parse(lastTime,format);

        List<String> orderNos = fetchTmsOrder.fetchPendingOrderNo(last.toDate());

        if(null==orderNos||orderNos.size()==0) {
            result.setMessage("无订单");
            return result;
        }

        TmsOrder tmsOrder;
        List<TmsOrder> tmsOrders = Lists.newArrayList();
        for (String orderNo:orderNos) {
            tmsOrder = fetchTmsOrder.fetchTmsOrderByOrderNo(orderNo);
            tmsOrders.add(tmsOrder);

            try {
                orderService.handleTmsOrders(tmsOrders);
            } catch (Exception e) {
                LOGGER.error("OrderServiceImpl.handleTmsOrders is error orderNo:{},e:{}.", orderNo,e);
            }
            tmsOrders.clear();
        }
        result.setData(orderNos);
        return result;
    }

}
